#define _CRT_SECURE_NO_WARNINGS
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
struct ListNode 
{
    int val;
    struct ListNode *next;
 };

struct ListNode* addTwoNumbers1(struct ListNode* l1, struct ListNode* l2)
{
    int a = 0;
    int b = 0;
    int count1 = 0;
    int count2 = 0;
    do
    {
        a += (l1->val) * pow(10, count1);
        l1 = l1->next;
        count1++;
    } while (l1 != NULL);
    do
    {
        b += (l2->val) * pow(10, count2);
        l2 = l2->next;
        count2++;
    } while (l2 != NULL);
    int count = count1 > count2 ? count1 : count2;
    struct ListNode* l3 = (struct ListNode*)calloc(count+1, sizeof(struct ListNode));
    int sum = a + b;
    int i = 0;
    for (i = 0; i < count; i++)
    {
        l3[i].val = sum % 10;
        sum /= 10;
        l3[i].next = &l3[i + 1];
    }
    if (count)
    {
        l3[count - 1].next = NULL;
    }
    return l3;
}

struct ListNode* addTwoNumbers2(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* head = NULL, * tail = NULL;
    int carry = 0;
    while (l1 || l2) {
        int n1 = l1 ? l1->val : 0;
        int n2 = l2 ? l2->val : 0;
        int sum = n1 + n2 + carry;
        if (!head) {
            head = tail = malloc(sizeof(struct ListNode));
            tail->val = sum % 10;
            tail->next = NULL;
        }
        else {
            tail->next = malloc(sizeof(struct ListNode));
            tail->next->val = sum % 10;
            tail = tail->next;
            tail->next = NULL;
        }
        carry = sum / 10;
        if (l1) {
            l1 = l1->next;
        }
        if (l2) {
            l2 = l2->next;
        }
    }
    if (carry > 0) {
        tail->next = malloc(sizeof(struct ListNode));
        tail->next->val = carry;
        tail->next->next = NULL;
    }
    return head;
}

struct ListNode* list_fill(int n)
{
    int len = 0;
    int tmp = n;
    while (tmp)
    {
        tmp /= 10;
        len++;
    }
    struct ListNode* l = (struct ListNode*)calloc(len+1, sizeof(struct ListNode));
    int i = 0;
    for (i = 0; i < len; i++)
    {
        l[i].val = n % 10;
        n /= 10;
        l[i].next = &l[i + 1];
    }
    return l;
}

int list_transform(struct ListNode* l)
{
    int a = 0;
    int count = 0;
    do
    {
        a += (l->val) * pow(10, count);
        l = l->next;
        count++;
    }while (l != NULL);
    return a;
}
int main()
{
    int x = 9;
    int y = 9;
    struct ListNode* l1= list_fill(x);
    struct ListNode* l2= list_fill(y);
    struct ListNode* l3=addTwoNumbers1(l1, l2);
    printf("%d", list_transform(l3));
    return 0;
}